//
//  HMXQQlistViewController.m
//  音乐播放器
//
//  Created by apple on 16/7/14.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "HMXQQlistViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <MJExtension/MJExtension.h>
#import "musicViewModel.h"
#import "HMXContentCell.h"
#import <AFNetworking/AFNetworking.h>

@interface HMXQQlistViewController ()<AVAudioPlayerDelegate>

@property(nonatomic,strong)AVPlayer * player;
@property(nonatomic,assign)NSInteger num;
@property(nonatomic,assign,getter=isPaused)BOOL Paused;//用于判断当前歌曲播放状态
@property(nonatomic,strong)NSMutableArray * muArr;
@property(nonatomic,strong)AFHTTPSessionManager * manager;

@end

@implementation HMXQQlistViewController

static NSString * const ID = @"cellID";

-(AFHTTPSessionManager *)manager
{
    if (_manager == nil) {
        
        _manager = [AFHTTPSessionManager manager];
    }
    return  _manager;
}

-(NSMutableArray *)muArr{
    
    if(_muArr == nil)
    {
        _muArr = [NSMutableArray array];
    }
    return _muArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.tableView registerClass:[HMXContentCell class] forCellReuseIdentifier:ID];
    
    self.tableView.backgroundColor = [UIColor lightGrayColor];
    
    [self loadNewData];
    
    self.title = @"Jaymusic";
    
    [self playMusicAtBackground];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    //第一个参数是观察者是谁
    //第二个是调用的方法
    //第三个是监听通知的名字
    //通知发送的对象，nil表示任何对象
    [center addObserver:self selector:@selector(receiveNoti:) name:@"hotLrcNotification" object:nil];
    
    [center addObserver:self selector:@selector(receiveNotiComment:) name:@"commentNotification" object:nil];
}
//4.响应
-(void)receiveNoti:(NSNotification*)noti
{
    UIButton * btn = [[UIButton alloc]init];
    btn =  noti.userInfo[@"BtnClick"] ;
    btn.selected = !btn.selected;
    
    UILabel * label = [[UILabel alloc]init];
    label = noti.userInfo[@"text"];
    NSInteger num = label.text.intValue;
    
    if(btn.selected){
        
        num = num + 1;
    
    }else{
    
        num = num - 1;
    }
    
    label.text = [NSString stringWithFormat:@"%ld",num];
}

//响应通知
-(void)receiveNotiComment:(NSNotification *)noti
{
    UIButton * btn = [[UIButton alloc]init];
    btn =  noti.userInfo[@"BtnClick"] ;
    btn.selected = !btn.selected;
    
    UILabel * label = [[UILabel alloc]init];
    label = noti.userInfo[@"text"];
    NSInteger num = label.text.intValue;
    
    if(btn.selected){
        
        num = num + 1;
        
    }else{
        
        num = num - 1;
    }
    
    label.text = [NSString stringWithFormat:@"%ld",num];
}

/**
 *  设置音乐可以在后台播放
 */
-(void)playMusicAtBackground{

    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    //让app支持接受远程控制事件
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

}

/**
 *  加载播放数据
 */
-(void)loadNewData{
    
    [self.manager GET:@"http://169.254.175.26:8080/musicservice/songs" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
        
        NSArray * arr =  responseObject[@"Music"];
        NSArray * muArr = [musicModel mj_objectArrayWithKeyValuesArray:arr];
        for (musicModel * item in muArr) {
            
            musicViewModel * vm = [[musicViewModel alloc]init];
            vm.item = item;
            [self.muArr addObject:vm];
        }
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
        NSLog(@"回调失败");
    }];
    
    NSLog(@"%@",self.muArr);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.num == indexPath.row && self.isPaused == NO) {
        
        [self.player pause];
        self.Paused = YES;
        return;
    }
    else if(self.num == indexPath.row && self.isPaused == YES){
        
        [self.player play];
        self.Paused = NO;
        //return;
    }
    else {
        
        
        
        musicViewModel * cellItem = self.muArr[indexPath.row];
        
        NSString * str = [cellItem.item.songUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL * url = [NSURL URLWithString: str];
        //NSLog(@"%@",cellItem.songUrl);
        
        self.num = indexPath.row;
        self.Paused = NO;
        
        self.player = [[AVPlayer alloc]initWithURL:url];
        NSLog(@"%@",url);
        [self.player play];
        
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    musicViewModel * vm = self.muArr[indexPath.row];
    return vm.cellH + 10;
}



#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.muArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    HMXContentCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    
    cell.vm = self.muArr[indexPath.row];
    
   
    return cell;
}




@end
